package DataAcess;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class BusReader {

    private ArrayList<Bus> arrbus;
    private ArrayList<Place> arrpPlaces;

    public BusReader() {
        arrbus = new ArrayList<>();
        try {
            FileInputStream fs = new FileInputStream("BusDB.txt");
            ObjectInputStream ois = new ObjectInputStream(fs);
            Bus bus;
            while (fs.available() != 0) {
                bus = (Bus) ois.readObject();
                arrbus.add(bus);
            }
            ois.close();
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println("De-Serialization ERROR:" + ex);
        }
    }

    public ArrayList getArrBus() {
        return arrbus;
    }

    public BusReader(String s) {

        arrpPlaces = new ArrayList<>();
        String[] place = new String[300];
        int i = 0;
        String[][] placePiece = new String[300][3];

        String readFromFile = readfile(s);
        if (readFromFile == null) {
            System.out.println("File Not Found!!");
        }

        StringBuilder sb = new StringBuilder(readFromFile);
        sb.deleteCharAt(0);
        readFromFile = sb.toString();

        place = readFromFile.split("\n");

        for (int j = 0; j < place.length; j++) {
            place[j] = place[j].substring(0, place[j].length() - 1);
        }

        for (int j = 0; j < place.length; j++) {
            if (!place[j].equals("\n")) {
                placePiece[j] = place[j].split("\\|");
                for (int k = 0; k < placePiece[j].length; k++) {
                    placePiece[j][k] = placePiece[j][k].replace("\\|", "");
                }
            }
        }
        for (int j = 0; j < place.length; j++) {
            Place place1 = new Place(placePiece[j][0], placePiece[j][1], placePiece[j][2]);
            arrpPlaces.add(place1);
        }
    }

    public ArrayList arrpPlaces() {
        return arrpPlaces;
    }

    private String readfile(String filename) {
        FileInputStream fin;
        try {
            fin = new FileInputStream(filename);
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found!");
            return null;
        }
        byte[] b = new byte[5000];
        try {
            fin.read(b);
        } catch (IOException e) {
            System.out.println("Read Error!");
        }
        String s = new String(b).trim();
        return s;

    }

//    public static void main(String[] args) {
//        BusReader br = new BusReader("famous.txt");
//    }
}
